<!-- src/components/MyChart.vue -->
<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

// 图表容器引用
const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
  // 销毁旧实例（防止重复初始化）
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 初始化 echarts 实例
  chartInstance = echarts.init(chartRef.value);

  // 配置项
  const option = {
    title: {
      text: "ECharts 示例",
    },
    tooltip: {},
    xAxis: {
      type: "category",
      data: ["A", "B", "C", "D", "E"],
    },
    yAxis: {},
    series: [
      {
        name: "销量",
        type: "bar",
        data: [120, 200, 150, 80, 70],
      },
    ],
  };

  // 设置配置项
  chartInstance.setOption(option);
};

// 页面挂载后初始化图表
onMounted(() => {
  initChart();
  // 监听窗口大小变化，响应式重绘
  window.addEventListener("resize", () => chartInstance?.resize());
});

// 组件销毁前清除事件监听和实例
onBeforeUnmount(() => {
  window.removeEventListener("resize", () => chartInstance?.resize());
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 400px"></div>
</template>
